package com.example.service.impl;

import com.example.entity.User;
import com.example.entity.UserDTO;
import com.example.mapper.UserMapper;
import com.example.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public User login(UserDTO userLoginDTO) throws Exception {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();

        password = DigestUtils.md5DigestAsHex(password.getBytes());
        log.info("加密后的密文是：{}",password);

        User user = userMapper.getByUsername(username);

        if(user == null){
            throw new Exception("账号不存在");
        }else if(!user.getPassword().equals(password)){
            throw new Exception("密码错误");
        }

        return user;
    }

    @Override
    public int exists(UserDTO userDTO) throws Exception {
        User user = userMapper.getByUsername(userDTO.getUsername());
        if(user != null){
            throw new Exception("用户已经存在");
        }
        if(userDTO.getPassword() == null){
            throw new Exception("密码不能为空");
        }
        String password = DigestUtils.md5DigestAsHex(userDTO.getPassword().getBytes());
        user.setPassword(password);
        user.setUsername(userDTO.getUsername());
        userMapper.insert(user);
        return userMapper.getByUsername(user.getUsername()).getId();
    }
}
